const Base = require('./base.js');

module.exports = class extends Base {
	constructor(ctx) {
		super(ctx);
		this.transfer = this.model("taoke/transfer");

	}
	async indexAction() {
		if(this.isGet) {
			return this.display();
		}

		let posts = this.post();
		let where = {};
		if(!think.isEmpty(posts.keyword)) {
			where.title = ['like', '%' + posts.keyword + '%'];
		}

		let fields = "id, title, org_price, price, quan_price, goods_id, commission, pic, tao_word, user_id, create_time";
		const data = await this.transfer.joinUserTable(posts, where, fields);
		return this.json(data);

	}
	//从商品信息生成高佣淘口令
	async taowordAction() {
		let goods = this.post("goods");
		//		goods = await this.model("goods").where({
		//			goods_id: '523278973634'
		//		}).find();
		const alimama = think.service("alimama");
		let result = await alimama.transferLink(goods.goods_id);
		console.log(result);
		//		if(!think.isEmpty(goods.quan_id)) {
		//			result.coupon_click_url = result.coupon_click_url + "&activityId=" + goods.quan_id;
		//		}
		if(think.isEmpty(result)) {
			return this.fail("转化失败");
		}
		let taoword = await alimama.getTaoword({
			'url': result.coupon_click_url,
			'text': goods.title,
			'logo': goods.pic
		});
		result.kouling = taoword.data.model;
		result.goods = goods;
		let user = await this.session("user");

		await this.transfer.add({
			"title": goods.title,
			"org_price": goods.org_price,
			"price": goods.price,
			"quan_price": goods.quan_price,
			"goods_id": goods.goods_id,
			"commission": goods.commission,
			"pic": goods.pic,
			"tao_word": result.kouling,
			"user_id": user.id,
			"create_time": new Date().valueOf()
		});
		return this.success(result);

	}
	//从普通淘口令或商品网址转化高佣淘口令
	async taowordTransferAction() {

		let info = this.post("info");
let user = await this.session("user");
		let result = await this.transfer.getTaoword(info,user.level);
		if(think.isEmpty(result)) {
			return this.fail("转化失败");
		}
		
		await this.transfer.add({
			"title": result.goods.title,
			"org_price": result.goods.zk_final_price,
			"price": result.final_price,
			"quan_price": result.coupon_amout,
			"goods_id": result.goods.num_iid,
			"commission": result.max_commission_rate,
			"pic": result.goods.pict_url,
			"tao_word": result.kouling,
			"user_id": user.id,
			"create_time": new Date().valueOf()
		});
		return this.success(result);
	}

};